import {observable, action, toJS} from 'mobx';
import {WeaTableNew, WeaForm} from 'comsMobx';
import {WeaLocaleProvider} from "ecCom";
import {message, Modal} from "antd";
import * as contractManagementApi from '../api/ContractManagementApi';
import LanguageConstant from '../constant/LanguageConstant';
import {indexOf, isBlank, parseIntValue} from '../util/CommonUtil';


const confirm = Modal.confirm
const {TableStore} = WeaTableNew;
const {getLabel} = WeaLocaleProvider;

/**
 * 模板store
 */
class MouldStore {

    /**
     * 是否有操作页面的权限
     *
     * @type {boolean}
     */
    @observable authorized = true;

    /**
     *是有拥有合同范本维护权限
     */
    @observable managementAuth = true;

    /**
     * 加载状态
     */
    @observable loading = false;

    /**
     * 分页控件的store
     */
    @observable tableStore = new TableStore();

    /**
     * 分类列表选择值
     *
     * @type {string}
     */
    @observable selectedRowKeys = "";

    /**
     * 删除按钮置灰
     *
     * @type {boolean}
     */
    @observable deleteBtnDisbled = true;

    /**
     * 弹出框是否显示
     *
     * @type {boolean}
     */
    @observable dialogVisible = false;

    /**
     * 是否是编辑
     *
     * @type {boolean}
     */
    @observable editMould = false;

    /**
     * 是否是编辑模板
     *
     * @type {boolean}
     */
    @observable addMould = false;

    /**
     * 是否编辑权限
     *
     * @type {boolean}
     */
    @observable editPermission = false;

    /**
     * 编辑权限的模板的id
     *
     * @type {number}
     */
    @observable editPermissionMouldId = -1;

    /**
     * 编辑的模板的主键
     *
     * @type {string}
     */
    @observable editRowKey = "";


    /**
     * 模板类型
     */
    @observable mouldType = -1;

    /**
     * 编辑表单
     *
     * @type {WeaForm}
     */
    @observable editMouldForm = new WeaForm();

    /**
     * 编辑模板字段
     *
     * @type {Array}
     */
    @observable editFormConditions = [];

    /**
     * 替换的文件id
     *
     * @type {Array}
     */
    @observable replacementFileId = [];

    /**
     * 模板树数据
     *
     * @type {Array}
     */
    @observable mouldTypeTreeDatas = [];

    /**
     * 模板树重新渲染
     *
     * @type {number}
     */
    @observable mouldTypeTreeRerender = 1;

    /**
     *模板树展开
     *
     * @type {string}
     */
    @observable mouldTypeTreeExpandedKeys = [];

    /**
     * 开启分权管理
     */
    @observable detachedMaintenance = false;

    /**
     * 选择的分部
     */
    @observable selectedSubCompanyId = -1;

    /**
     * 模板树展开事件
     *
     * @param keys
     * @param node
     */
    @action
    onMouldTypeTreeExpand = (keys, node) => {
        this.mouldTypeTreeExpandedKeys = keys;
    }

    /**
     * 模板数据选择
     *
     * @param key
     * @param count
     * @param countType
     */
    @action
    onMouldTypeTreeSelect = (key, count, countType) => {
        if (key.indexOf("type_") == 0) {
            let type = key.split("_")[1];
            const subCompanyId = toJS(this.selectedSubCompanyId);
            const params = {type, subCompanyId};
            this.getTableData(params);
            this.mouldType = type;
        }
    }

    /**
     * 获取模板类型树
     *
     */
    @action
    getMouldTypeTree = () => {
        contractManagementApi.getMouldTypeTree().then(res => {
            const {code, data} = res;
            if (code == 200) {
                this.mouldTypeTreeDatas = data;
            }
        });
    }

    /**
     * 分部树选择对应数据
     *
     * @param params
     */
    onSelectBySubcompany = (params = {}) => {
        const {subCompanyId} = params;
        this.selectedSubCompanyId = subCompanyId;
        const mouldType = toJS(this.mouldType);
        const queryDatas = {type: mouldType, subCompanyId: subCompanyId};
        this.getTableData(queryDatas);
    }

    /**
     * 加载系统设置
     */
    @action
    getSystemSetting = () => {
        contractManagementApi.getSystemSetting().then(res => {
            const {code, data} = res;
            if (code == 200) {
                const {detachedMaintenance} = data;
                this.detachedMaintenance = detachedMaintenance;
            }
        });
    }

    /**
     * 获取列表数据
     * @param params
     */
    @action
    getTableData = (params) => {
        this.loading = true;
        contractManagementApi.getMouldList(params).then(res => {
            this.loading = false;
            const {code, data} = res;
            if (code == 401) {
                this.authorized = false;
            } else if (code == 200) {
                const {managementAuth, sessionkey} = data;
                this.managementAuth = managementAuth;
                this.tableStore.getDatas(sessionkey);
            }
        });
    }

    /**
     * 重置打开弹框相关参数
     */
    @action
    resetOpenDialogMethod = () => {
        this.addMould = false;
        this.editMould = false;
        this.editPermission = false;
        this.editPermissionMouldId = -1;
    }

    /**
     * 打开弹框
     * @param params
     */
    @action
    openDialog = (method, id) => {
        this.resetOpenDialogMethod();
        if (method == "editMould" && id) {
            this.getMouldEditForm({id, method: 'edit'});
            this.editRowKey = id;
            this.editMould = true;
        } else if (method == "addMould") {
            this.addMould = true;
        } else if (method == "editPermission" && id) {
            this.editPermission = true;
            this.editPermissionMouldId = id;
        }
        this.dialogVisible = true;
    }

    /**
     * 获取模板编辑表单
     *
     * @param params
     */
    @action
    getMouldEditForm = (params) => {
        this.loading = true;
        contractManagementApi.getMouldEditForm(params).then(res => {
            this.loading = false;
            const {code, data} = res;
            if (code == 200 && data) {
                this.editMouldForm = new WeaForm();
                this.editMouldForm.initFormFields(data);
                this.editFormConditions = data;
            }
        });
    }

    /**
     * 保存编辑模板表单数据
     */
    @action
    saveEditForm = () => {
        const formDatas = this.editMouldForm.getFormParams();
        if (formDatas) {
            let name = formDatas.name;
            if (name == undefined || name.trim() == "") {
                message.error(getLabel(LanguageConstant.PLEASE_FILL_MUSTINPUT_FIELD, "请填写必填内容"));
                return;
            }
            let type = formDatas.type;
            if (type == undefined || type == "") {
                message.error(getLabel(LanguageConstant.PLEASE_FILL_MUSTINPUT_FIELD, "请填写必填内容"));
                return;
            }
        }
        this.editMouldForm.validateForm().then(f => {
            if (f.isValid) {
                this.onSaveEditForm();
            } else {
                f.showErrors();
            }
        });
    }

    /**
     * 保存编辑模板表单数据
     */
    @action
    onSaveEditForm = () => {
        const formDatas = this.editMouldForm.getFormParams();
        const id = this.editRowKey;
        const replacementFileId = toJS(this.replacementFileId)[0];
        const params = {
            ...formDatas, id, replacementFileId
        }
        this.loading = true;
        contractManagementApi.editMould(params).then(res => {
            this.loading = false;
            const {code, data} = res;
            if (code == 200) {
                this.selectedRowKeys = [];
                this.deleteBtnDisbled = true;
                this.closeDialog();
                this.getTableData();
                message.success(getLabel("518560", "操作成功"));
            } else {
                message.error(getLabel("518561", "操作失败"));
            }
        });
    }


    /**
     * 关闭新建编辑弹框
     */
    @action
    closeDialog = () => {
        this.dialogVisible = false;
        this.resetOpenDialogMethod();
    }


    /**
     * 列表check框选择事件
     *
     * @param selectedKeys
     * @param selectedInfo
     */
    rowSelection = (selectedKeys, selectedInfo) => {
        console.log("rowSelection", selectedKeys);
        this.selectedRowKeys = selectedKeys;
        this.deleteBtnDisbled = selectedKeys.length > 0 ? false : true;
    }

    /**
     * 删除模板数据
     *
     * @param ids
     * @param multiDelete
     */
    @action
    affirmDelete = (ids, multiDelete) => {
        if (multiDelete) {
            if (this.selectedRowKeys.length <= 0) {
                message.error(getLabel("518571", "请先选择待删除数据"));
                return;
            }
            ids = this.selectedRowKeys.join(",");
        }
        confirm({
            title: getLabel('518566', "信息确认"),
            content: getLabel('518567', "确定要删除吗？"),
            okText: getLabel('518568', "是"),
            cancelText: getLabel('518569', "否"),
            onOk: () => this.deleteMould({ids}),
            onCancel() {
            },
        });
    }

    /**
     * 删除模板数据
     *
     * @param params
     */
    deleteMould(params) {
        contractManagementApi.deleteMould(params).then(res => {
            const {code} = res;
            if (code == 200) {
                message.success(getLabel("518560", "操作成功"));
                this.getTableData();
                this.deleteBtnDisbled = true;
                this.selectedRowKeys = [];
            } else {
                message.error(getLabel("518561", "操作失败"));
            }
        });
    }

    /**
     * 分页列表操作动作
     *
     * @param record
     * @param index
     * @param operate
     * @param flag
     */
    @action
    onOperatesClick = (record, index, operate, flag) => {
        flag == "0" && this.openDialog("editMould", record.id);
        flag == "1" && this.download(record.fileId);
        flag == "2" && this.affirmDelete(record.id);
        flag == "3" && this.openDialog("editPermission", record.id);
    }

    /**
     * 下载模板文件
     *
     * @param fileId
     */
    download = (fileId) => {
        fileId = parseIntValue(fileId, -1);
        if (fileId > 0) {
            open(`/contractmanagement/downloadMouldFile?fileid=${fileId}&download=1`);
        }
    }

    /**
     * 替换文件字段改变事件处理
     *
     * @param ids
     * @param list
     */
    @action
    uploadMouldChange = (ids, list) => {
        this.replacementFileId = ids;
    }

}

export default MouldStore;